package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CollegeQueryRequest;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.entity.College;
import com.pn.taikao.service.CollegeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/colleges")
public class CollegeController {

    private final CollegeService collegeService;

    public CollegeController(CollegeService collegeService) {
        this.collegeService = collegeService;
    }

    /**
     * 创建学院
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<CreateResponse> create(@RequestBody College college) {
        Long id = collegeService.createCollege(college);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新学院
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody College college) {
        college.setId(id);
        collegeService.updateCollege(college);
        return ApiResponse.success(null);
    }

    /**
     * 删除学院
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        collegeService.deleteCollege(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询学院详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<College> detail(@PathVariable("id") Long id) {
        College college = collegeService.getById(id);
        if (college == null) {
            return ApiResponse.error("学院不存在");
        }
        return ApiResponse.success(college);
    }

    /**
     * 获取所有学院（不分页，用于下拉选择）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<List<College>> getAll() {
        List<College> colleges = collegeService.getAll();
        return ApiResponse.success(colleges);
    }

    /**
     * 分页查询学院列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<College>> list(@RequestBody CollegeQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        List<College> data = collegeService.list(request.getName(), page, size);
        long total = collegeService.count(request.getName());
        PageResult<College> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}











